<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Corp\Action\Dashboard;

use Exception;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Action\Dashboard\Traits\ValidateTokenTrait;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 企业微信授权- 配置客户联系.
 *
 * Class ContactSecretStore.
 * @Controller
 */
class ContactSecretStore extends AbstractAction
{
    use ValidateSceneTrait;
    use ValidateTokenTrait;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/dashboard/corp/contactSecretStore", methods="post")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @return array
     * @throws Exception 异常处理
     */
    public function handle()
    {
        // 接收参数
        $params = [
            'contactSecret' => trim($this->request->input('contactSecret')),
            'corpId' => (int) user()['corpIds'][0],
        ];
        // 参数验证
        $this->validated($this->request->all(), 'store');
        $corp = $this->corpService->getCorpById($params['corpId'], ['wx_corpid']);

        try {
            $result = $this->validateToken($corp['wxCorpid'], $params['contactSecret']);
            if ($result['errcode'] !== 0) {
                switch ($result['errcode']) {
                    case 40001:
                        throw new CommonException(ErrorCode::SERVER_ERROR, '客户联系Secret参数不合法');
                        break;
                    case 40013:
                        throw new CommonException(ErrorCode::SERVER_ERROR, '不合法的CorpID');
                        break;
                    default:
                        throw new CommonException(ErrorCode::SERVER_ERROR, '验证客户联系Secret失败，原因：' . $result['errmsg']);
                        break;
                }
            }
        } catch (\Throwable $e) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '请输入正确的客户联系Secret');
        }

        // 数据操作
        Db::beginTransaction();
        try {
            // 企业授信
            $this->corpService->updateCorpById($params['corpId'], ['contact_secret' => $params['contactSecret']]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '客户联系Secret创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, '客户联系Secret创建失败');
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'contactSecret' => 'required | string | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'contactSecret.required' => '客户联系Secret 必填',
            'contactSecret.string' => '客户联系Secret 必须为字符串',
        ];
    }
}
